# -*- coding: utf-8 -*- 
"""
Created by hcx on 2017/6/9 14:44.
@author: 胡超翔
"""
from __future__ import absolute_import
from __future__ import unicode_literals

import logging
import os
import uuid

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from autodeploy import settings

logger = logging.getLogger(__name__)


@csrf_exempt
def uploadify_script(request):
    ret = "0"
    file = request.FILES.get("Filedata", None)
    pbid = request.GET.get("pbid", None)
    version = request.POST.get("version", None)
    state = request.GET.get('state', '')
    new_name = ''
    if file:
        result, new_name, path = profile_upload(pbid, version, file, state)
        logger.info('path:%s' % path)
        if result:
            ret = "1"
    json = {'ret': ret, 'save_name': new_name, 'path': path}
    return JsonResponse(json)


def profile_upload(pbid, version, file, state=None):
    '''''文件上传函数'''
    file_name = ''
    path_file = ''
    # 文件名
    if pbid and version:
        dire_name = '%s_%s' % (pbid, version)
    else:
        return (False, file_name, path_file)
    if file:
        path = os.path.join(settings.MEDIA_ROOT, dire_name)
        # 创建文件夹
        status, final_path = create_dire(path)
        # if status:
        if state == 'zip':
            file_name = file.name
        # file_name=str(uuid.uuid1())+".jpg"
        else:
            # path = os.path.join(settings.MEDIA_ROOT, 'task')
            file_name = str(uuid.uuid1()) + '-' + file.name
        # fname = os.path.join(settings.MEDIA_ROOT,filename)
        path_file = os.path.join(final_path, file_name)
        fp = open(path_file, 'wb')
        for content in file.chunks():
            fp.write(content)
        fp.close()
        return (True, file_name, path_file)  # change
        # else:
    return (False, file_name, path_file)  # change


def create_dire(dire_path):
    # 引入模块
    import os

    # 去除首位空格
    path = dire_path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")

    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)

    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        logger.info(path + ' 创建成功')
        # print path+' 创建成功'
        return True, path
    else:
        # 如果目录存在则不创建，并提示目录已存在
        # print path+' 目录已存在'
        logger.info(path + ' 目录已存在')
        return False, path


def delete_dire(path):
    """删除文件夹"""
    import os
    isExists = os.path.exists(path)
    if isExists:
        os.popen('rm -rf %s' % path)
        msg = "删除成功"
        return True, msg
    else:
        msg = "删除失败，文件夹不存在"
        return False, msg
